package com.nf.practice.downloadFile;

import cn.hutool.http.HttpUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import org.jsoup.helper.StringUtil;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

public class PicDownloadByHtool {

    private static final List<String> jpgDir = Arrays.asList(
            "B",
            "B01",
            "B02"
    );

    private static final List<String> pdfDir = Arrays.asList(
            "XW"
    );

    private static final List<String> filterDir = Arrays.asList(
            "B",
            "G",
            "XW"
    );

    // 借款合同+放款凭证
    private final List<String> targetDir = Arrays.asList(
            "O01",
            "S01",
            "S03",
            "AA05",
            "AB05",
            "AC02",
            "AC03",
            "AE03",
            "AE04",
            "AF01",
            "AG02",
            "K",
            "M",
            "R",
            "S",
            "XW4",
            "XMHT",
            "GXHT",
            "O",
            "AD02",
            "Z01",
            "AH01",
            "AA07",
            "AI02",
            "U04",
            "U08",
            "U09",
            "U11",
            "U15",
            "AJ05",
            "AK05",
            "AK07",
            "AE07",
            "Z02",
            "AJ07",
            "J07",
            "J08",
            "J09",
            "J10",
            "ZY01"
    );

    private final List<String> loanContractDirs = Arrays.asList(
            "O01",
            "S01",
            "S03",
            "AA05",
            "AB05",
            "AC02",
            "AC03",
            "AE03",
            "AE04",
            "AF01",
            "AG02",
            "K",
            "M",
            "R",
            "S",
            "XW4",
            "XMHT",
            "GXHT",
            "O",
            "AD02",
            "Z01",
            "AH01",
            "AA07",
            "AI02",
            "U04",
            "U08",
            "U09",
            "U11",
            "U15",
            "AJ05",
            "AK05",
            "AK07"
    );

    private final List<String> fkDirs = Arrays.asList(
            "AE07",
            "Z02",
            "AJ07",
            "J07",
            "J08",
            "J09",
            "J10",
            "ZY01"
    );


    @Test
    public void picDownload() {
        String preDic = "C:/20240925诉讼影像/";
        // 创建Excel读取对象，传入文件路径
        ExcelReader reader = ExcelUtil.getReader("E:\\诉讼人员数据.xlsx");
        // 读取第一个sheet页面的所有数据，结果是一个List<List<Object>>，每个内部List代表一行数据
        List<List<Object>> dataList = reader.read();
        // 遍历并打印每行数据
        // 第一行数据不要
        Map<String,String> loanNoMap = new HashMap<>();
        for (int i = 1; i < dataList.size(); i++) {
            List<Object> row = dataList.get(i);
            if (null != row.get(1) && null != row.get(2)) {
                // <单号,借据号>
                loanNoMap.put(row.get(2).toString().trim(), row.get(1).toString().trim());
            }
        }

        ExcelReader reader2 = ExcelUtil.getReader("E:\\诉讼影像资料个人.xlsx");
        // 读取第一个sheet页面的所有数据，结果是一个List<List<Object>>，每个内部List代表一行数据
        List<List<Object>> dataList2 = reader2.read();
        List<PicExportDetail2> picDataList = new ArrayList<>();
        for (int i = 1; i < dataList2.size(); i++) {
            int idNoNum = 0;
            int loanContractNum = 0;
            int guaranteeContractNum = 0;
            PicExportDetail2 data = new PicExportDetail2();

            List<Object> row = dataList2.get(i);
            // 文件地址
            String appNo = "";
            String subclassSort = "";
            String fileUrl = "";
            if (null != row.get(0) && null != row.get(1) && null != row.get(2)) {
                subclassSort = row.get(1).toString().trim();
                if (!targetDir.contains(subclassSort)) {
                    continue;
                }

                appNo = loanNoMap.get(row.get(0).toString().trim());
                if (!StringUtils.isNotBlank(appNo)) {
                    System.out.println(row.get(0).toString().trim() + "该单号未找到借据号！");
                    continue;
                }
                fileUrl = row.get(2).toString().trim();
            } else {
                continue;
            }
//            if (!(subclassSort.startsWith("B") || subclassSort.startsWith("G") || subclassSort.startsWith("XW"))) {
//                continue;
//            }
            // 文件名
            String fileName = fileUrl;
            int lastIndex = fileName.lastIndexOf('/');
            if (lastIndex != -1) {
                // 截取最后一个'/'之后的所有字符
                fileName = subclassSort + "_" + fileName.substring(lastIndex + 1);
//                if (jpgDir.contains(subclassSort) && (!fileName.contains(".jpg") || !fileName.contains(".png"))) {
//                    fileName = fileName.concat(".jpg");
//                } else if (pdfDir.contains(subclassSort) && !fileName.contains(".pdf")) {
//                    fileName = fileName.concat(".pdf");
//                }
            }

            // 子目录创建
//            String subDir = "";
//            if (subclassSort.startsWith("B")) {
//                subDir = "B";
//            } else if (subclassSort.startsWith("G")) {
//                subDir = "G";
//            } else if (subclassSort.startsWith("XW")) {
//                subDir = "XW";
//            }
            String directoryPath = preDic + appNo + "/" + subclassSort + "/";

            File directory = new File(directoryPath);
            // 如果目录不存在，则创建它
            if (!directory.exists()) {
                directory.mkdirs();
            }
            // 创建文件对象，使用fileName作为文件名
            File file = new File(directory, fileName);
            // 使用Hutool的HttpUtil工具类下载影像件文件,文件保存的关键步骤
            try {
                HttpUtil.downloadFile(fileUrl, file);
            } catch (Exception e) {
                System.out.println(appNo + "-" + fileUrl + "-" + "下载失败!");
                // 下载异常了重新下载其他文件
                continue;
            }
            System.out.println(appNo + "-" + fileUrl + "-" + "下载成功!");
            if (loanContractDirs.contains(subclassSort)) {
                loanContractNum++;
            } else if (fkDirs.contains(subclassSort)) {
                guaranteeContractNum++;
            }
            data.setAppNo(appNo)
                    .setIdNoNum(idNoNum)
                    .setLoanContractNum(loanContractNum)
                    .setGuaranteeContractNum(guaranteeContractNum);
            picDataList.add(data);
        }

        Map<String, PicExportDetail2> groupedData = picDataList.stream()
                .collect(Collectors.groupingBy(
                        PicExportDetail2::getAppNo, // 按照 appNo 分组
                        Collectors.collectingAndThen(
                                Collectors.reducing((d1, d2) -> d1.merge(d2)), // 使用自定义的merge方法进行归约
                                Optional::get // 从Optional中获取结果
                        )
                ));

        // 输出结果
        List<PicExportDetail2> finalDataList = new ArrayList<>();
        groupedData.forEach((appNo, data) -> {
            finalDataList.add(data);
        });
        File directory = new File(preDic);
        // 如果目录不存在，则创建它
        if (!directory.exists()) {
            directory.mkdirs();
        }
        ExcelWriter writer = ExcelUtil.getWriter(new File(preDic + "fsFinalFile.xlsx"));
        if(!CollectionUtils.isEmpty(finalDataList)){
            writer.setSheet(0).write(finalDataList);
            writer.flush();
        }

        // 关闭读取器，释放资源
        reader.close();
        reader2.close();
    }

}
